package com.javasm.adminapi.module.product.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javasm.adminapi.common.exception.ExceptionEnum;
import com.javasm.adminapi.common.exception.JavasmException;
import com.javasm.adminapi.module.product.dao.TBrandDao;
import com.javasm.adminapi.module.product.entity.TBrand;
import com.javasm.adminapi.module.product.service.TBrandService;
import com.javasm.adminapi.module.system.entity.User;
import com.javasm.adminapi.module.system.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.SecureRandom;
import java.util.Date;
import java.util.List;

/**
 * 品牌表(TBrand)表服务实现类
 *
 * @author makejava
 * @since 2025-10-14 22:29:06
 */
@Service("tBrandService")
public class TBrandServiceImpl extends ServiceImpl<TBrandDao, TBrand> implements TBrandService {

    @Override
    public PageInfo<TBrand> listByPage(Integer pageNum, Integer pageSize, String brandName, Integer isEnabled) {
        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<TBrand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TBrand::getIsDeleted,0);
        if (brandName != null){
            queryWrapper.like(TBrand::getBrandName,brandName);
        }
        if (isEnabled != null){
            queryWrapper.eq(TBrand::getIsEnabled,isEnabled);
        }
        queryWrapper.eq(TBrand::getIsDeleted,0);
        List<TBrand> list = this.list(queryWrapper);
        return new PageInfo<>(list);
    }
    @Resource
    UserService userService;
    @Override
    public boolean addTBrand(TBrand tBrand) {
        System.out.println("=====================");
        System.out.println(tBrand);
        tBrand.setCreatedTime(new Date());
//        String s = generateUniqueSpuNoWithTimestamp();
        //判断s是否在数据库中
        boolean b = true;
        while (b){
            String s = generateUniqueSpuNoWithTimestamp();
            TBrand bySpuNo = this.getOne(new LambdaQueryWrapper<TBrand>().eq(TBrand::getBrandNum,s));
            if (bySpuNo == null){
                tBrand.setBrandNum(s);
                b =false;
            }
        }
        if (tBrand.getCateId() == null){
            tBrand.setCateId(0);
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            String username = ((UserDetails) authentication.getPrincipal()).getUsername();
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, username);
            User user = userService.getByUsername(username);
            tBrand.setCreatedBy(String.valueOf(user.getId()));
        }
        return this.save(tBrand);
    }

    @Override
    public boolean updateByIdinfo(TBrand tBrand) {
        tBrand.setUpdatedTime(new Date());
        if (tBrand.getCateId() == null){
            throw new JavasmException(ExceptionEnum.Category_Null);
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            String username = ((UserDetails) authentication.getPrincipal()).getUsername();
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, username);
            User user = userService.getByUsername(username);
            tBrand.setUpdatedBy(String.valueOf(user.getId()));
        }
        //生成一个六位的随机数
        int randomNumber = (int) (Math.random() * 9000000) + 1000000;
        tBrand.setSortOrder(String.valueOf(randomNumber));
        return this.updateById(tBrand);
    }
//删除方法
    @Override
    public boolean removeByIdsInfo(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        // 批量更新 is_deleted 字段为 1（表示已删除）
        LambdaQueryWrapper<TBrand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(TBrand::getId, ids);
        TBrand updateBrand = new TBrand();
        updateBrand.setIsDeleted(1);
        return this.update(updateBrand, queryWrapper);
    }

    @Override
    public List<TBrand> listall1() {
        LambdaQueryWrapper<TBrand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TBrand::getIsDeleted,0);
        return this.list(queryWrapper);
    }

    private String generateUniqueSpuNoWithTimestamp() {
        // 使用时间戳+随机数的方式，减少碰撞概率
        long timestamp = System.currentTimeMillis() % 100000000;
        int random = (int) (Math.random() * 100);
        return String.format("PP%08d%01d", timestamp, random);
    }
}

